package org.budo.support.servlet.util;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.budo.support.java.collection.wrapper.NiceToStringMapWrapper;
import org.budo.support.lang.util.StringUtil;

/**
 * @author limingwei2
 */
public class QueryStringUtil {
    public static String mapToQueryString(Map parameterMap) {
        String parameterString = "";
        if (null == parameterMap || parameterMap.isEmpty()) {
            return parameterString;
        }

        boolean first = true;
        for (Object each : parameterMap.entrySet()) {
            Entry entry = (Entry) each;
            Object key = entry.getKey();
            Object value = entry.getValue();
            if (null == value) {
                continue;
            }

            Object[] valueArray = value.getClass().isArray() ? (Object[]) value : new Object[] { value };
            for (Object valueEach : valueArray) {
                if (!first) {
                    parameterString += "&";
                } else {
                    first = false;
                }

                parameterString += key + "=" + valueEach;
            }
        }

        return parameterString;
    }

    public static Map<String, String[]> queryStringToMap(String queryString) {
        if (StringUtil.isEmpty(queryString)) {
            return new HashMap<String, String[]>();
        }

        if (queryString.startsWith("?")) {
            queryString = queryString.substring(1);
        }

        Map<String, List<String>> map = new HashMap<String, List<String>>();
        String[] pairs = queryString.split("&");

        for (String pair : pairs) {
            String[] keyValue = pair.split("=");
            String key = keyValue[0];
            String value = keyValue.length == 1 ? null : keyValue[1];
            List<String> values = map.get(key);

            if (null == values) {
                values = new ArrayList<String>();
                values.add(value);
                map.put(key, values);
            } else {
                values.add(value);
            }
        }

        Map<String, String[]> result = new HashMap<String, String[]>();
        for (Entry<String, List<String>> entry : map.entrySet()) {
            List<String> value = entry.getValue();
            String[] array = value.toArray(new String[value.size()]);
            result.put(entry.getKey(), array);
        }

        return new NiceToStringMapWrapper(result);
    }
}